<?php

namespace App\Http\Controllers\Admin;

use App\Models\Images;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ImagesController extends Controller
{
    //
    public $imagesModel;
    public function __construct()
    {
        $this->imagesModel = new Images();
    }
    public function uploadImages(Request $request){
        $file = $request->file('file');
        if ($file->isValid()) {
            if (in_array(strtolower($file->getClientOriginalExtension()), ['jpeg', 'jpg', 'gif', 'png'])) {
                $newFileName = date('YmdHis') . mt_rand(100, 900) . "." . $file->getClientOriginalExtension();
                if ($file->move(public_path() . '/uploads/' . date('Ymd'), $newFileName)) {
                    $data['img_url']=asset('/uploads/' . date('Ymd') . '/' . $newFileName);
                    $data['img_ext'] = $file->getClientOriginalExtension();
                    $data['created_at'] = date("Y-m-d H:i:s");
                    $data['updated_at']=date("Y-m-d H:i:s");
                    $data['img_size'] = $file->getMaxFilesize();
                    $res = $this->imagesModel->add($data);
                    if($res){
                        return response()->json(['code' => 0, 'msg' => '', 'data' => ['id'=>$res,'src' => asset('/uploads/' . date('Ymd') . '/' . $newFileName), 'title' => '']]);
                    }else{
                        return response()->json(['code' => 404, 'msg' => '图片上传失败！']);
                    }
                } else {
                    return response()->json(['code' => 404, 'msg' => '图片存储失败！']);
                }
            } else {
                return response()->json(['code' => 404, 'msg' => '上传图片格式不正确！']);
            }
        } else {
            return response()->json(['code' => 404, 'msg' => '图片上传失败！']);
        }

    }

}
